;;;
;;; JaCoLiB
;;; Copyright (C) 2008 Alessandro Serra
;;; 
;;; This program is free software: you can redistribute it and/or modify
;;; it under the terms of the GNU General Public License as published by
;;; the Free Software Foundation, either version 3 of the License, or
;;; (at your option) any later version.
;;; 
;;; This program is distributed in the hope that it will be useful,
;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;;; GNU General Public License for more details.
;;; 
;;; You should have received a copy of the GNU General Public License
;;; along with this program.  If not, see <http://www.gnu.org/licenses/>.
;;;

;;;; Created on 2008-07-23 09:58:11

(in-package :jacolib)

(defun jacolib-init-connection (jacolib connection name)
  (let* ((channel (jacolib-new-shell-channel jacolib name))
         (rpc-connection (make-instance 'rpc-connection
                                        :connection connection
                                        :rpc-channel channel)))
    (values (rpc-channel-client channel) channel rpc-connection)))
    
(defun jacolib-connect (jacolib name host port secret)
  (let ((client (make-instance 'jacolib::client-connector 
                               :host host 
                               :port port 
                               :secret-string secret)))
    (jacolib-init-connection jacolib (jacolib::client-connector-connect client) name)))

(defun jacolib-connect-and-loop (jacolib name host port secret)
  (multiple-value-bind (remote-shell channel rpc-connection) (jacolib-connect jacolib name host port secret)
    (declare (ignore remote-shell)
             (ignore channel))
    (rpc-connection-loop-until-quit rpc-connection)))

(defun jacolib-start-server (jacolib name-prefix port secret ump)
  (let* ((i 0)
         (server (make-instance 'jacolib::server-connector 
                                :port port 
                                :secret-string secret
                                :use-multi-threadp ump
                                :connection-handler #'(lambda (connection) 
                                                        (multiple-value-bind (remote-shell channel rpc-connection)
                                                          (jacolib-init-connection jacolib connection (format nil "~A~D" name-prefix i))
                                                          (declare (ignore remote-shell)
                                                                   (ignore channel))
                                                          (setf i (+ 1 i))                                   
                                                          (rpc-connection-loop-until-quit rpc-connection))))))
    (server-connector-run server)))
